package com.zyylc.wine.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.zyylc.wine.util.RequestUtil;
import com.zyylc.wine.util.Result;
import com.zyylc.wine.util.XmlHelper;

@Component
public class BaseController {
	private static Log logger = LogFactory.getLog(BaseController.class);

	protected static final String XML_TYPE = "xml";
	protected static final String JSON_TYPE = "json";

	/**
	 * @param type
	 * @param obj
	 * @return
	 */
	public String response(String type, Object obj) {
		if (XML_TYPE.equalsIgnoreCase(type)) {
			String ret = XmlHelper.marshal(obj);
			logger.info("======controller 返回结果===============" + ret + "=====================");
			return ret;
		}
		if (JSON_TYPE.equalsIgnoreCase(type)) {
			String ret = JSONObject.toJSONString(obj);
			logger.info("======controller 返回结果===============" + ret + "=====================");
			return ret;
		}
		return "";
	}

	/**
	 * ctrl 返回json数据
	 * 
	 * @Description 默认结果状态 code -1 状态描述 成功
	 * @param object 返回的数据
	 * @return
	 * @author: zj
	 */
	public String jsonResponse(Object object) {
		Result<Object> result = new Result<Object>();
		result.setData(object);
		return this.response(JSON_TYPE, result);
	}

	/**
	 * ctrl 返回json数据
	 * 
	 * @Description (TODO这里用一句话描述这个方法的作用)
	 * @param object 返回的数据
	 * @param code   返回的结果状态code
	 * @param msg    返回结果的状态描述
	 * @return
	 * @author: zj
	 */
	public String jsonResponse(Object object, String code, String msg) {
		Result<Object> result = new Result<Object>(code, msg);
		result.setData(object);
		return this.response(JSON_TYPE, result);
	}

	public static void main(String[] args) {

		List<String> languages = Arrays.asList("java", "scala", "python");
		languages.forEach(aa -> System.out.println(aa));
		List<Double> cost = Arrays.asList(10.0, 20.0, 30.0);
		cost.stream().map(x -> x + x * 0.05).forEach(x -> System.out.println(x));
	}

	/**
	 * * 获取请求传递过来的参数
	 * 
	 * @Description (TODO这里用一句话描述这个方法的作用)
	 * @param request
	 * @return 将参数封装到Map对象中，参数名称就是map的key
	 * @author: zj
	 */
	public Map<String, String> getParamValues(HttpServletRequest req) {
		return RequestUtil.paramToMap(req);
	}
}
